package com.tianqu.tms.www.car.action;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.validator.Resources;
import org.jbarcode.JBarcode;
import org.jbarcode.encode.Code39Encoder;
import org.jbarcode.encode.EAN13Encoder;
import org.jbarcode.paint.BaseLineTextPainter;
import org.jbarcode.paint.EAN13TextPainter;
import org.jbarcode.paint.WideRatioCodedPainter;
import org.jbarcode.paint.WidthCodedPainter;
import org.jbarcode.util.ImageUtil;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsAction;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.util.DateUtil;
import com.tianqu.tms.core.util.FieldChecker;
import com.tianqu.tms.core.util.ImageUtils;
import com.tianqu.tms.core.util.Registry;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.core.util.TmsFieldChecks;
import com.tianqu.tms.dao.MemberDao;
import com.tianqu.tms.dao.TmsDao;
import com.tianqu.tms.dto.MemberDto;
import com.tianqu.tms.entity.Car;
import com.tianqu.tms.entity.Codes;
import com.tianqu.tms.entity.Member;
import com.tianqu.tms.www.car.actionform.CarCreationInputActionForm;
import com.tianqu.tms.www.car.controller.CarCreationEasyInputResultCopntroller;
import com.tianqu.tms.www.car.viewhelper.CarCreationInputViewHelper;

/**
 * @author zhangxueliang
 * 立体停车场入库结果action
 */
public class CarCreationEasyInputResultAction extends TmsAction{
	private Logger logger = Logger.getLogger(CarCreationEasyInputResultAction.class);
	private static final String BACKFLAG = "backFlag";
	private static final String TOEASYINPUT = "toEasyInput";
	private static final String OFF="off";
	@Override
	protected ActionForward doAction(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response,
			UserContext uc) throws Exception {
		logger.debug(this.getClass().getName() + "#execute was called.");
		isToken(mapping, request);
		CarCreationInputViewHelper viewhelper = new CarCreationInputViewHelper();
		viewhelper = (CarCreationInputViewHelper)uc.getAttribute(VIEWHELP);
		String path =ImageUtils.getImageDirectoryPath(Registry.getConfig(TmsConstants.UPLOADTMP_CONTEXT_ROOT_KEY));
		viewhelper.setImagePath(path);
		uc.setAttribute("result","ok");
		
		String strQRPrintFlg = viewhelper.getQRPrintFlg();
		
		//check
		String licensePlate = viewhelper.getLicensePlate();
		String lPlate = Registry.getConfig(TmsConstants.TMS_DEFLICENSEPLATE_KEY);//车牌前两位
		if(lPlate.equals(viewhelper.getLicensePlate())){
			licensePlate ="";
			
		}
		
	    if(!StringUtil.isNullOrBlank(licensePlate) && !TmsFieldChecks.isCarLicense(licensePlate) ){
        	setErrorsToRequest(request, TmsConstants.U1002 ,null);
        	if (StringUtil.isNullOrBlank(licensePlate)) viewhelper.setLicensePlate(lPlate);
			return  mapping.findForward(TOEASYINPUT);
	    }
		  
//		if (!StringUtil.isNullOrBlank(viewhelper.getTempLicensePlate())) {
//			try {
//				if(FieldChecker.isNumericalSt(viewhelper.getTempLicensePlate())){
//					setErrorsToRequest(request, TmsConstants.U11001, null);
//					if (StringUtil.isNullOrBlank(licensePlate)) viewhelper.setLicensePlate(lPlate);
//					return mapping.findForward(TOEASYINPUT);
//				}
//				if(GenericValidator.matchRegexp(viewhelper.getTempLicensePlate(),"^[a-zA-Z]*$")){
//					setErrorsToRequest(request, TmsConstants.U11001, null);
//					if (StringUtil.isNullOrBlank(licensePlate)) viewhelper.setLicensePlate(lPlate);
//					return mapping.findForward(TOEASYINPUT);
//				}
//				if (!GenericValidator.matchRegexp(viewhelper.getTempLicensePlate(),"^[0-9a-zA-Z]*$")) {
//					setErrorsToRequest(request, TmsConstants.U11001, null);
//					if (StringUtil.isNullOrBlank(licensePlate)) viewhelper.setLicensePlate(lPlate);
//					return mapping.findForward(TOEASYINPUT);
//				}
//
//			} catch (Exception e) {
//				setErrorsToRequest(request, TmsConstants.U11001, null);
//				if (StringUtil.isNullOrBlank(licensePlate)) viewhelper.setLicensePlate(lPlate);
//				return mapping.findForward(TOEASYINPUT);
//			}	
//		}
		
//		String gateType = viewhelper.getGateType();
//		if ("3".endsWith(gateType)) {
//			if(StringUtil.isNullOrBlank(licensePlate) && StringUtil.isNullOrBlank(viewhelper.getTempLicensePlate())){
//				if (StringUtil.isNullOrBlank(licensePlate)) viewhelper.setLicensePlate(lPlate);
//				setErrorsToRequest(request, TmsConstants.U8005 ,null);
//				return mapping.findForward(TOEASYINPUT);
//			}			
//		}else if("1".endsWith(gateType)){
//			if(StringUtil.isNullOrBlank(viewhelper.getTempLicensePlate())){
//				if (StringUtil.isNullOrBlank(licensePlate)) viewhelper.setLicensePlate(lPlate);
//				String[] param = {"易碎贴编号"};
//				setErrorsToRequest(request, TmsConstants.U0005 ,param);
//				return mapping.findForward(TOEASYINPUT);
//			}
//		}
		  
		Car carNew = Car.getInstance();
		Member member = Member.getInstance();
		if(!StringUtil.isNullOrBlank(viewhelper.getLicensePlate()) ){
			carNew = carNew.findCarByLicensePlate(viewhelper.getLicensePlate(),1);
			if(!StringUtil.isNullOrBlank(carNew.getSerial())){
				if (StringUtil.isNullOrBlank(licensePlate)) viewhelper.setLicensePlate(lPlate);
				member = member.findMemberInfoByMemId(String.valueOf(carNew.getMemberId()));
				String[] param = {member.getShortName()};
				setErrorsToRequest(request, TmsConstants.U1029 ,param);//车牌号码已经被登记使用，不能重复使用。
				return mapping.findForward(TOEASYINPUT);
			}
		} 
		if(!StringUtil.isNullOrBlank(viewhelper.getTempLicensePlate())){
			carNew = carNew.findCarByLicensePlate(viewhelper.getTempLicensePlate(),2);
			if(!StringUtil.isNullOrBlank(carNew.getSerial())){
				if (StringUtil.isNullOrBlank(licensePlate)) viewhelper.setLicensePlate(lPlate);
				member = member.findMemberInfoByMemId(String.valueOf(carNew.getMemberId()));
				String[] param = {member.getShortName()};
				setErrorsToRequest(request, TmsConstants.U8008 ,param);	//临时车牌号码已经使用，不能重复使用.
				return mapping.findForward(TOEASYINPUT);
			}
		}
		
		// 对车架号是否已经使用进行check
		Car carInfo = Car.getInstance();
		String memberId = carInfo.vinCheck(viewhelper.getVin());

		if (!StringUtil.isNullOrBlank(memberId)) {
			
			MemberDao mDao = (MemberDao) TmsDao.getInstance(TmsDao.TMS_MEMBER);
			MemberDto memberDto = mDao.findMemberInfoByMemId(memberId);
			String[] param = {memberDto.getShortName()};
			setErrorsToRequest(request, TmsConstants.U8007, param); // 输入的车架号已经被【{0}】登记使用，不能重复登记。
			if (StringUtil.isNullOrBlank(licensePlate)) viewhelper.setLicensePlate(lPlate);
			return mapping.findForward(TOEASYINPUT);
		}
		member = member.findMemberInfoByMemId(viewhelper.getMemberId());
		int annualTransactionVolume = member.getAnnualTransactionVolume();
		int alreadyTransactionVolume = carInfo.getAlreadyTransactionVolumeByMemberId(String.valueOf(viewhelper.getMemberId()));
		if (alreadyTransactionVolume >= annualTransactionVolume) {
			setErrorsToRequest(request, TmsConstants.U8004, null); // 当前商户的允许登记数量已经用完，无法进行保存。
			if (StringUtil.isNullOrBlank(licensePlate)) viewhelper.setLicensePlate(lPlate);
			return mapping.findForward(TOEASYINPUT);
		}
		
		if (!StringUtil.isNullOrBlank(viewhelper.getJqx())
				&& !StringUtil.isNullOrBlank(viewhelper.getRegDate())){
			
			if (Integer.parseInt(viewhelper.getJqx().replaceAll("-", "")) < Integer.parseInt(viewhelper.getRegDate().replaceAll("-", ""))) {
			
				String[] param = {"交强险日期","登记日期"};
				setErrorsToRequest(request, TmsConstants.U0036, param); //交强险日期填写的日期不能比登记日期填写的日期小。
				if (StringUtil.isNullOrBlank(licensePlate)) viewhelper.setLicensePlate(lPlate);
				return mapping.findForward(TOEASYINPUT);
			}
		}
			
		if (!StringUtil.isNullOrBlank(viewhelper.getYearCarefulPeriod())
				&& !StringUtil.isNullOrBlank(viewhelper.getRegDate())){
			
			if (Integer.parseInt(viewhelper.getYearCarefulPeriod().replaceAll("-", "")) < Integer.parseInt(viewhelper.getRegDate().replaceAll("-", ""))) {
				String[] param = {"年检日期","登记日期"};
				setErrorsToRequest(request, TmsConstants.U0036, param); //年检日期填写的日期不能比登记日期填写的日期小。
				if (StringUtil.isNullOrBlank(licensePlate)) viewhelper.setLicensePlate(lPlate);
				return mapping.findForward(TOEASYINPUT);
			}
		}
	    //
		if(viewhelper.getSaveFlag() ==3){
			if(viewhelper.getAttestStatus() == 1){
				//打出提示信息   认证状态请选择认证！
				setErrorsToRequest(request, TmsConstants.IA006 ,null);
				request.setAttribute(TmsConstants.VIEWHELP, viewhelper);
				return mapping.getInputForward();
			}
		}
		//查验表判断过户第一张图片是否为空
		if(viewhelper.getSaveFlag() ==7){
			if(StringUtil.isNullOrBlank(viewhelper.getTransferPhoto())){
				//打出提示信息   查验照片不能为空！
				setErrorsToRequest(request, TmsConstants.IA007 ,null);
				request.setAttribute(TmsConstants.VIEWHELP, viewhelper);
				return mapping.getInputForward();
			}
		}
		
		CarCreationEasyInputResultCopntroller controller = new CarCreationEasyInputResultCopntroller();
		controller.execute(uc);
		request.setAttribute(OFF, "信息保存成功!");
		viewhelper = (CarCreationInputViewHelper)uc.getAttribute(VIEWHELP);
		if(viewhelper.getInsertFlag() == 3){
			//打出提示信息   车辆通过查验照相正处于过户中！
			setErrorsToRequest(request, TmsConstants.IM040 ,null);
			request.setAttribute(TmsConstants.VIEWHELP, viewhelper);
			return mapping.getInputForward();
		}
		//add by huangheli at 20150908 start
		else if(viewhelper.getInsertFlag() == 9){
			//打出提示信息   车辆已经在库登记，不能重复登记！
			setErrorsToRequest(request, TmsConstants.IA002 ,null);
			request.setAttribute(TmsConstants.VIEWHELP, viewhelper);
			return mapping.getInputForward();
		}
		//add by huangheli at 20150908 end
		Codes code = Codes.getInstance();
		if(!StringUtil.isNullOrBlank(viewhelper.getGearbox())){
			viewhelper.setGearbox(code.getItemValueByItemIdAndItemCode(Codes.GEARBOX_TYPE, Integer.parseInt(viewhelper.getGearbox())));
		}else{
			viewhelper.setGearbox("");
		}
		if("MT".equals(viewhelper.getGearbox())){
			viewhelper.setGearbox("手动");
		}
		if("AT".equals(viewhelper.getGearbox())){
			viewhelper.setGearbox("自动");
		}
		if("A/MT".equals(viewhelper.getGearbox())){
			viewhelper.setGearbox("手自一体");
		}
		
		if(viewhelper.getSaveFlag() != 1){
			
		String onOff = "";
		onOff = Registry.getConfig(TmsConstants.WWW_IMAGE_ON_KEY);//1.开 2.关
		if(viewhelper.getSaveFlag() == 5){
			viewhelper.setPrintType("a3");
			if("1".equals(onOff)){
				//未认证
				if(viewhelper.getAttestStatus() == 1){
					viewhelper.setImageOn("1");
				}else if(viewhelper.getAttestStatus() == 2){
					viewhelper.setImageOn("2");//认证
				}			
			}else{
				viewhelper.setImageOn("3");//无底板图片
			}
			try {  
	            JBarcode localJBarcode = new JBarcode(EAN13Encoder.getInstance(),WidthCodedPainter.getInstance(),EAN13TextPainter.getInstance());  
	            
	            String str = viewhelper.getTransferSerial()+viewhelper.getSerial(); 
	          
	            //BufferedImage localBufferedImage = localJBarcode.createBarcode(str);  
	            
	            //saveToJPEG(localBufferedImage, "EAN13.jpg");
	            localJBarcode.setEncoder(Code39Encoder.getInstance());   
	            localJBarcode.setPainter(WideRatioCodedPainter.getInstance());   
	            localJBarcode.setTextPainter(BaseLineTextPainter.getInstance());   
	            localJBarcode.setShowCheckDigit(false);   
	           
            	BufferedImage localBufferedImage = localJBarcode.createBarcode(str); 
 	            String paramString = str+".jpg";           
 	            viewhelper.setTiaoImage(Registry.getConfig(TmsConstants.WWW_UPLOAD_TIAO_UPLOAD_KEY)+"/"+paramString);
            	File file  = new File(path);
			    if (!file.exists()) {
			    	file.mkdirs();
				}
			   
            	FileOutputStream localFileOutputStream = new FileOutputStream(path+"/" + paramString);  
                ImageUtil.encodeAndWrite(localBufferedImage, "jpeg", localFileOutputStream, 96, 96);  
                localFileOutputStream.close();
	           }catch (Exception e) {  
	        	 logger.error("createBarcode error",e);
	           }
		}	
		if(viewhelper.getSaveFlag() ==3){
			viewhelper.setRzFlag("on");//打印检测报告
			viewhelper.setPrintType("a3");
		}
		
		if(viewhelper.getSaveFlag() == 7){//打印查验表
			viewhelper.setCheckOk("ok");
			viewhelper.setPrintType("a4");
			viewhelper.setCardType(code.getItemValueByItemIdAndItemCode(Codes.PLATE_TYPE, Integer.parseInt(viewhelper.getCardType())));
		}
		if(viewhelper.getSaveFlag() == 6){//打印流程表
			viewhelper.setLiuchengOk("ok");
			viewhelper.setPrintType("a4");
			viewhelper.setLiuTime(DateUtil.getCurrentTimeStr3());
			
		}
		Member mem = Member.getInstance();
		viewhelper.setMemberName(mem.getMemNameByMemId(Integer.parseInt(viewhelper.getMemberId())));
          

		viewhelper.setPrintFlag("1");
		}
		uc.setAttribute(BACKFLAG, 1);
		request.removeAttribute(TmsConstants.VIEWHELP);
		uc.removeAttribute(TmsConstants.VIEWHELP);
		uc.removeAttribute("result");
		
		if ("2".equals(strQRPrintFlg)) {
			uc.setAttribute("QRPrintSerial", viewhelper.getSerial());
		} else {
			uc.removeAttribute("QRPrintSerial");
		}
		
		logger.debug(this.getClass().getName() + "#execute was completed.");
		return mapping.findForward(TmsConstants.SUCCESS);
	}
}
